package com.cykj.shop.service.impl;

/**
 * @BelongsProject: Cykj-Order-System
 * @BelongsPackage: com.cykj.shop.service.impl
 * @Author: cwx
 * @CreateTime: 2025/8/25 10:49
 * @Description:
 * @Version: 1.0
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cykj.shop.domain.dto.HotKeywordDTO;
import com.cykj.shop.domain.dto.ShopInfoDTO;
import com.cykj.system.api.domain.Shop;
import com.cykj.shop.mapper.CsShopMapper;
import com.cykj.shop.mapper.ShopCategoryMapper;
import com.cykj.shop.service.IShopService;
import com.cykj.system.api.domain.ShopCategory;
import com.cykj.system.api.domain.ShopCategoryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
@Service
public class CsShopServiceimpl implements IShopService {

    @Autowired
    private CsShopMapper shopMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ShopCategoryMapper shopCategoryMapper;

    @Override
    public List<ShopInfoDTO> getNearbyShops(
            Double longitude, Double latitude, Double distance,
            Integer shopCategory, String keyword,
            Double minGrade, Double maxGrade, Integer pageSize) {
        List<ShopInfoDTO> shops = shopMapper.selectNearbyShops(
                longitude, latitude, distance, shopCategory, keyword, minGrade, maxGrade, pageSize
        );
        shops.forEach(shop -> {
            if (shop.getProducts() == null || shop.getProducts().isEmpty()) {
                log.warn("店铺[{}]无商品数据: {}", shop.getId(), shop.getProducts());
            }
        });

        return shops;
    }

    @Override
    public List<ShopCategoryVo> getShopCategories() {
        List<ShopCategory> categories = shopCategoryMapper.selectList(
                new QueryWrapper<ShopCategory>().eq("status", 1)
        );
        return categories.stream().map(category -> {
            ShopCategoryVo vo = new ShopCategoryVo();
            vo.setId(category.getId());
            vo.setName(category.getName());
            return vo;
        }).collect(Collectors.toList());
    }
    @Override
    public Shop selectShopById(Long id) {
        return shopMapper.selectShopById(id);
    }

    // 新增方法实现
    /**
     * 1. 记录搜索关键词（Redis有序集合，按热度排序）
     */
    @Override
    public void recordSearchKeyword(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return;
        }
        String redisKey = "shop:hot_keywords";
        // 累加热度
        redisTemplate.opsForZSet().incrementScore(redisKey, keyword.trim(), 1);
    }

    /**
     * 2. 获取Top10热搜词（倒序，热度从高到低）
     */
    @Override
    public List<HotKeywordDTO> getHotKeywords() {
        String redisKey = "shop:hot_keywords";
        // reverseRangeWithScores：倒序获取0-9索引（Top10），包含分数
        Set<ZSetOperations.TypedTuple<Object>> topKeywords =
                redisTemplate.opsForZSet().reverseRangeWithScores(redisKey, 0, 9);

        if (topKeywords == null || topKeywords.isEmpty()) {
            return Collections.emptyList();  // 替换List.of()
        }
        return topKeywords.stream()
                .map(tuple -> new HotKeywordDTO(
                        tuple.getValue().toString(),
                        tuple.getScore() != null ? tuple.getScore() : 0.0
                ))
                .collect(Collectors.toList());
    }

    /**
     * 3. 搜索店铺（复用getNearbyShops逻辑，自动记录关键词热度）
     */
    @Override
    public List<ShopInfoDTO> searchShops(Double longitude, Double latitude, Double distance,
                                         String keyword, Double minGrade, Double maxGrade, Integer pageSize) {
        // 记录搜索关键词（自动去重+累加热度）
        this.recordSearchKeyword(keyword);

        // 复用附近店铺查询逻辑（无需分类筛选，shopCategory传null）
        return this.getNearbyShops(
                longitude, latitude, distance,
                null, // 搜索页无需分类筛选
                keyword, minGrade, maxGrade, pageSize
        );
    }
}
